{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Hardware Design"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This code works through the hardware design process with the the\n",
    "audience of software developers more in mind.  We start with the simple\n",
    "problem of designing a fibonacci sequence calculator (http://oeis.org/A000045)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pyrtl"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### A normal old python function to return the Nth fibonacci number.\n",
    "\n",
    "Interative implementation of fibonacci, just iteratively adds a and b to\n",
    "calculate the nth number in the sequence.\n",
    "```>> [software_fibonacci(x) for x in range(10)]\n",
    "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def software_fibonacci(n):\n",
    "    a, b = 0, 1\n",
    "    for i in range(n):\n",
    "        a, b = b, a + b\n",
    "    return a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attempt 1\n",
    "\n",
    "Let's convert this into some hardware that computes the same thing. Our first go will be to just replace the 0 and 1 with WireVectors to see\n",
    "what happens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def attempt1_hardware_fibonacci(n, bitwidth):\n",
    "    a = pyrtl.Const(0)\n",
    "    b = pyrtl.Const(1)\n",
    "    for i in range(n):\n",
    "        a, b = b, a + b\n",
    "    return a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The above looks really nice does not really represent a hardware implementation\n",
    "of fibonacci.\n",
    "\n",
    "Let's reason through the code, line by line, to figure out what it would actually build.\n",
    "\n",
    "* **```a = pyrtl.Const(0)```**\n",
    "> This makes a wirevector of ```bitwidth=1``` that is driven by a zero.  Thus **```a```** is a wirevector.  Seems good.\n",
    "\n",
    "* **```b = pyrtl.Const(1)```**       \n",
    "> Just like above, ```b``` is a wirevector driven by 1\n",
    "\n",
    "* **```for i in range(n):```**\n",
    "> Okay, here is where things start to go off the rails a bit. This says to perform the following code 'n' times, but the value 'n' is passed as an input and is not something that is evaluated in the hardware, it is evaluated when you run the PyRTL program which generates (or more specifically elaborates) the hardware. Thus the hardware we are building will have The value of 'n' built into the hardware and won't actually be a run-time parameter. Loops are really useful for building large repetitive hardware structures, but they CAN'T be used to represent hardware that should do a computation iteratively. Instead we are going to need to use some registers to build a state machine.\n",
    "* **```a, b = b, a + b```**\n",
    "> Let's break this apart. In the first cycle **```b```** is ```Const(1)``` and ```(a + b)``` builds an adder with a ```(Const(0))``` and ```b (Const(1)``` as inputs. Thus ```(b, a + b)``` in the first iteration is: ```( Const(1), result_of_adding( Const(0), Const(1) )``` At the end of the first iteration **```a```** and **```b```** refer to those two constant values. In each following iteration more adders are built and the names **```a```** and **```b```** are bound to larger and larger trees of adders but all the inputs are constants!\n",
    "* **```return a```**              \n",
    "> The final thing that is returned then is the last output from this tree of adders which all have ```Consts``` as inputs. Thus this hardware is hard-wired to find only and exactly the value of fibonacci of the value N specified at design time! Probably not what you are intending."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attempt 2\n",
    "\n",
    "Let's try a different approach. Let's specify two registers (\"a\" and \"b\") and then we can **update those values** as we iteratively compute fibonacci of N **cycle by cycle.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def attempt2_hardware_fibonacci(n, bitwidth):\n",
    "    a = pyrtl.Register(bitwidth, 'a')\n",
    "    b = pyrtl.Register(bitwidth, 'b')\n",
    "\n",
    "    a.next <<= b\n",
    "    b.next <<= a + b\n",
    "\n",
    "    return a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is looking much better.  \n",
    "\n",
    "Two registers, **```a```** and **```b```** store the values from which we\n",
    "can compute the series.  \n",
    "\n",
    "The line ```a.next <<= b``` means that the value of a in the next\n",
    "cycle should be simply be **```b```** from the current cycle.\n",
    "\n",
    "The line ```b.next <<= a + b``` says\n",
    "to build an adder, with inputs of **```a```** and **```b```** from the current cycle and assign the value\n",
    "to **```b```** in the next cycle.\n",
    "\n",
    "### A visual representation of the hardware built is as such:\n",
    "```\n",
    "      +-----+      +---------+\n",
    "      |     |      |         |\n",
    "  +===V==+  |  +===V==+      |\n",
    "  |      |  |  |      |      |\n",
    "  |   a  |  |  |   b  |      |\n",
    "  |      |  |  |      |      |\n",
    "  +===V==+  |  +==V===+      |\n",
    "      |     |     |          |\n",
    "      |     +-----+          |\n",
    "      |           |          |\n",
    "  +===V===========V==+       |\n",
    "   \\      adder     /        |\n",
    "    +==============+         |\n",
    "             |               |\n",
    "             +---------------+\n",
    "```\n",
    "\n",
    "\n",
    "Note that in the picture the register **```a```** and **```b```** each have a wirevector which is\n",
    "the current value (shown flowing out of the bottom of the register) and an *input*\n",
    "which is giving the value that should be the value of the register in the following\n",
    "cycle (shown flowing into the top of the register) which are **```a```** and **```a.next```** respectively.\n",
    "\n",
    "When we say **```return a```** what we are returning is a reference to the register **```a```** in\n",
    "the picture above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attempt 3\n",
    "\n",
    "Of course one problem is that we don't know when we are done! **How do we know we\n",
    "reached the \"nth\" number in the sequence?**  Well, we need to **add a register** to\n",
    "count up and see if we are done.\n",
    "\n",
    "This is very similliar to the example before, except that now we have a register \"i\"\n",
    "which keeps track of the iteration that we are on (i.next <<= i + 1).\n",
    "\n",
    "The **function now returns two values**, a reference to the register \"a\" and a reference to a single\n",
    "bit that tells us if we are done. That bit is calculated by comparing \"i\" to the\n",
    "to a wirevector \"n\" that is passed in to see if they are the same.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def attempt3_hardware_fibonacci(n, bitwidth):\n",
    "    a = pyrtl.Register(bitwidth, 'a')\n",
    "    b = pyrtl.Register(bitwidth, 'b')\n",
    "    i = pyrtl.Register(bitwidth, 'i')\n",
    "\n",
    "    i.next <<= i + 1\n",
    "    a.next <<= b\n",
    "    b.next <<= a + b\n",
    "\n",
    "    return a, i == n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attempt 4\n",
    "\n",
    "This is now far enough along that we can **simulate the design** and see what happens..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def attempt4_hardware_fibonacci(n, req, bitwidth):\n",
    "    a = pyrtl.Register(bitwidth, 'a')\n",
    "    b = pyrtl.Register(bitwidth, 'b')\n",
    "    i = pyrtl.Register(bitwidth, 'i')\n",
    "    local_n = pyrtl.Register(bitwidth, 'local_n')\n",
    "    done = pyrtl.WireVector(bitwidth=1, name='done')\n",
    "\n",
    "    with pyrtl.conditional_assignment:\n",
    "        with req:\n",
    "            local_n.next |= n\n",
    "            i.next |= 0\n",
    "            a.next |= 0\n",
    "            b.next |= 1\n",
    "        with pyrtl.otherwise:\n",
    "            i.next |= i + 1\n",
    "            a.next |= b\n",
    "            b.next |= a + b\n",
    "    done <<= i == local_n\n",
    "    return a, done"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
